//
//  Toast.swift
//  ADKit
//
//  Created by Adoma on 2020/10/22.
//

import UIKit
import MBProgressHUD

public class ADToast {
    
    public class Config {
        public static let shared = Config()
        
        public var yOffset: CGFloat = 0.35
        public var titleFont: UIFont = UIFont.pingfang(with: 15)
    }
    
    static var shared = ADToast()
        
    weak var hud: MBProgressHUD? {
        didSet {
            DispatchQueue.main.async {
                oldValue?.removeFromSuperview()
            }
        }
    }
    
    public static func show(loading tip: String) {
        
        guard let window = WindowManager.keyWindow else {
            return
        }
                
        let hud = MBProgressHUD.showAdded(to: window, animated: true)
        hud.label.text = tip
        hud.label.font = Config.shared.titleFont
        hud.bezelView.color = UIColor.black
        hud.contentColor = UIColor.white
        hud.isSquare = true
        hud.margin = 10
        
        ADToast.shared.hud = hud
    }
    
    public static func show(msg: String, hideDelay: Double = 0) {
        
        guard let window = WindowManager.keyWindow else {
            return
        }
                
        let hud = MBProgressHUD.showAdded(to: window, animated: true)
        hud.mode = .text
        hud.label.text = msg
        hud.label.font = Config.shared.titleFont
        hud.label.numberOfLines = 0
        hud.bezelView.color = UIColor.black
        hud.contentColor = UIColor.white
        hud.margin = 10
        hud.isUserInteractionEnabled = false

        let yOffset = Config.shared.yOffset
        if yOffset > 0 {
            hud.offset = .init(x: 0, y: kScreenHeight * yOffset)
        }
        
        if hideDelay > 0 {
            hud.hide(animated: true, afterDelay: hideDelay)
        } else {
            hud.hide(animated: true, afterDelay: max(Double(msg.count/8), 1.5))
        }
        
        ADToast.shared.hud = hud
    }
    
    public static func hide(animated: Bool = false) {
        ADToast.shared.hud?.hide(animated: animated)
    }
}
